package com.zdltech.lightappupdatelib;

import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.zdltech.lightappupdatelib.core.AppVersionConvert;
import com.zdltech.lightappupdatelib.core.AppVersionConvertCallback;
import com.zdltech.lightappupdatelib.core.LightConstant;
import com.zdltech.lightappupdatelib.core.UpdateCallback;
import com.zdltech.lightappupdatelib.core.UpdateDialogFragment;
import com.zdltech.lightappupdatelib.entity.AppVertionEntity;
import com.zdltech.lightappupdatelib.net.HttpCoreManager;
import com.zdltech.lightappupdatelib.net.HttpManager;
import com.zdltech.lightappupdatelib.service.DownloadCallback;
import com.zdltech.lightappupdatelib.service.DownloadService;
import com.zdltech.lightappupdatelib.utils.LightAppUpdateUtils;
import com.zdltech.lightappupdatelib.utils.LogUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jason on 2017/8/28.
 *
 * @ Des
 * @ Author jason
 */

public class LightUpdateManager {
    //输出日志时用
    private static final String TAG = LightUpdateManager.class.getSimpleName();

    public static String  mUpdateUrl;//更新的路径

    /**
     * 可以直接利用下载功能，
     *
     * @param context          上下文
     * @param updateAppBean    下载信息配置
     * @param downloadCallback 下载回调
     */
    public static void download(final Context context, @NonNull final AppVertionEntity updateAppBean, @Nullable final DownloadCallback downloadCallback) {
        if (updateAppBean == null) {
            throw new NullPointerException("updateApp 不能为空");
        }
        if ("apk".equals(updateAppBean.getUpdateType())){//下载
            DownloadService.bindService(context.getApplicationContext(), new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    ((DownloadService.DownloadBinder) service).start(updateAppBean, downloadCallback);
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            });
        }else{//
            Toast.makeText(context,"不支持下载",Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 检测是否有新版本
     *
     * @param callback 更新回调
     */
    public static void checkNewApp(Context mActivity, final UpdateCallback callback, boolean isPost, Map<String, String> mParams) {
        checkNewApp(mActivity,callback,isPost,mParams,null);
    }
    /**
     * 检测是否有新版本
     * 自定义数据转换（支持自定义数椐转换为工厂统一对象处理）
     *
     * @param callback 更新回调
     */
    public static void checkNewApp(Context mActivity, final UpdateCallback callback, boolean isPost, Map<String, String> mParams, final AppVersionConvertCallback convertCallback) {
        if (callback == null) {
            return;
        }
        if (mUpdateUrl==null){
            throw new NullPointerException("更新的路径不能为空");
        }
        callback.start();

        if (DownloadService.isRunning || UpdateDialogFragment.isShow) {
            callback.end();
            Toast.makeText(mActivity, "app正在更新", Toast.LENGTH_SHORT).show();
            return;
        }

        //拼接参数
        Map<String, String> params = new HashMap<String, String>();

        int versionCode = LightAppUpdateUtils.getVersionCode(mActivity);
        params.put("version", versionCode+"");
        params.put("platform", "android");//固定写法 android平台
        params.put("appUnique",LightAppUpdateUtils.getPackageName(mActivity));

        //添加自定义参数，其实可以实现HttManager中添加
        if (mParams != null && !mParams.isEmpty()) {
            //清空，那就使用自定参数
            params.clear();
            params.putAll(mParams);
        }

        //网络请求
        if (isPost) {
            HttpCoreManager.getInstance().asyncPost(mUpdateUrl, params, new HttpManager.Callback() {
                @Override
                public void onResponse(String result) {
                    LogUtils.e("result="+result);
                    if (result != null) {
                        processData(result, callback,convertCallback);
                    }
                    callback.end();
                }

                @Override
                public void onError(String error) {
                    callback.error(-1,error);
                    callback.end();
                    LogUtils.e("error="+error);
                }
            });
        } else {
            HttpCoreManager.getInstance().asyncGet(mUpdateUrl, params, new HttpManager.Callback() {
                @Override
                public void onResponse(String result) {
                    if (result != null) {
                        processData(result, callback,convertCallback);
                    }
                    callback.end();
                }

                @Override
                public void onError(String error) {
                    LogUtils.e("error="+error);
                    callback.error(-1,error);
                    callback.end();
                }
            });
        }
    }

    /**
     * 数据解析--自定义数据转换的
     * @param result
     * @param callback
     */
    private static void processData(String result, UpdateCallback callback,AppVersionConvertCallback convertCallback) {

        if (callback!=null){
            if (convertCallback!=null){//自定义数据转换
                LogUtils.e("数据解析 自定义 result="+result);
                callback.update(AppVersionConvert.parseOhter(result,convertCallback));
            }else{
                callback.update(AppVersionConvert.parseJson(result));
            }
        }

    }


    /**
     *  下载完成-提示更新 可以当做静默更新
     *  用户联网检查更新，如果是下载完成 提醒更新，否则如果是不Wifi下，就什么都不做，在wifi下自动下载
     *  如果用户设置了 不在Wifi下也更新的话，都更新
     * @param mActivity
     * @param updateApp
     * @throws Exception
     */
    public static final void hasNewApp(final Context mActivity, final AppVertionEntity updateApp) throws Exception{
        //添加信息
        AppVertionEntity updateAppBean = updateApp;
        //设置不显示通知栏下载进度
        updateAppBean.setmDismissNotificationProgress(true);

        if (LightAppUpdateUtils.appIsDownloaded(updateApp)) {
            showDialog(mActivity,updateApp);
        } else {
            //假如是onlyWifi,则进行判断网络环境
            if (LightConstant.ISONLY_WIFI && !LightAppUpdateUtils.isWifi(mActivity)) {
                //要求是wifi下，且当前不是wifi环境
                return;
            }
            download(mActivity,updateAppBean,new DownloadCallback() {
                @Override
                public void onStart() {

                }

                @Override
                public void onProgress(float progress, long totalSize) {

                }

                @Override
                public void setMax(long totalSize) {

                }

                @Override
                public boolean onFinish(File file) {
                    showDialog(mActivity,updateApp);
                    return false;
                }


                @Override
                public void onError(String msg) {

                }
            });
        }
    }

    /**
     * 使用默认对话框，
     *
     */
    public static void showDialog(Context mActivity,AppVertionEntity updateApp) {
        showDialogFragment(mActivity,updateApp,0,0);
    }


    /**
     * 跳转到更新页面
     */
    public static void showDialogFragment(Context mActivity,AppVertionEntity version,int mThemeColor,int mTopPic) {
        //校验-是否显示更新对话框
        if (verify(mActivity,version)) return;
        if (mActivity != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(LightConstant.INTENT_ITEM, version);
            if (mThemeColor != 0) {
                bundle.putInt(LightConstant.THEME_KEY, mThemeColor);
            }
            if (mTopPic != 0) {
                bundle.putInt(LightConstant.TOP_IMAGE_KEY, mTopPic);
            }
            UpdateDialogFragment updateDialogFragment = new UpdateDialogFragment();
            updateDialogFragment.setArguments(bundle);
            updateDialogFragment.show(((FragmentActivity) mActivity).getSupportFragmentManager(), "dialog");
        }
    }

    /**
     * 校验版本 是否忽略
     * @return
     */
    public static boolean verify(Context mContext,AppVertionEntity version){
        //版本忽略
        if (LightAppUpdateUtils.isNeedIgnore(mContext, version.getVersion()+"")) {
            return true;
        }else {
            return false;
        }
    }
}
